<template>
    <div class="contener">
        <div class="page">
            <!-- 搜索 -->
            <transition
                @before-enter="_beforeEnter"
                @enter="_enter"
                @after-enter="_afterEnter"
                @before-leave="_beforeLeave"
                @leave="_leave"
                @after-leave="_afterLeave"
            >
                <div
                    class="search-contener"
                    ref="searchContener"
                    v-show="searchFormConfig.searchContenerShow"
                >
                    <base-form
                        :formItems="searchFormConfig.formItems"
                        :formData="searchFormConfig.formSubmit"
                        ref="searchForm"
                        @onButtonClick="searchButtonClick"
                    />
                </div>
            </transition>
            <!-- 表格 -->
            <div class="datas-contener">
                <!-- 表格操作项 -->
                <div class="option-contener">
                    <data-options
                        @buttonClick="handelOptionClick"
                        :leftConfig="dataOptionConfig.leftConfig"
                    />
                </div>
                <!-- 表格展示项 -->
                <div class="table-contener">
                    <base-table
                        ref="baseTable"
                        :tableData="baseTableConfig.tableData"
                        :tableHeader="baseTableConfig.tableHeader"
                        :tableConfig="baseTableConfig.tableConfig"
                        @handleSelection="tableDataSelected"
                    >
                        <template slot-scope="{ scope }">
                            <span v-if="scope.type === 'index'">
                                {{ scope.$index }}
                            </span>
                            <div v-if="scope.type === 'handle'">
                                <el-button
                                    type="text"
                                    @click.stop="updateTableData(scope.row)"
                                    v-hasPermi="['device/dict/update']"
                                    >修改</el-button
                                >
                                <el-button
                                    type="text"
                                    @click.stop="deleteTableData(scope.row)"
                                    v-hasPermi="['device/dict/delete']"
                                    >删除</el-button
                                >
                            </div>
                        </template>
                    </base-table>
                </div>
                <!-- 分页 -->
                <div class="paging-contener">
                    <pagin-ation
                        :size="paginationConfig.size"
                        :total="paginationConfig.total"
                        :type="paginationConfig.type"
                        @PageNumber="pageNumberChange"
                        @PageSize="pageSizeChange"
                    />
                </div>
            </div>
        </div>
        <!-- 弹框 -->
        <el-dialog
            :title="dialogConfig.title"
            :visible.sync="dialogConfig.show"
            :width="dialogConfig.width"
            v-dialogDrag
        >
            <!-- 筛选表格列 -->
            <div v-if="dialogConfig.key === 'tableColumn'">
                <base-transfer
                    :transferConfig="tableColumnTransferConfig"
                    ref="baseTransfer"
                />
            </div>
            <!-- 新增 -->
            <div v-if="dialogConfig.key === 'addTableData'">
                <base-form
                    :formItems="addFormConfig.formItems"
                    :formData="addFormConfig.formSubmit"
                    :formConfig="addFormConfig.formConfig"
                    :formRules="addFormConfig.formRule"
                    ref="addForm"
                    @onButtonClick="addFormButtonClick"
                >
                    <template slot="uploadBoundry">
                        <div class="upload-container">
                            <el-row>
                                <el-col :span="2">
                                    <span class="logo-title">图标</span>
                                </el-col>
                                <el-col :span="16">
                                    <el-upload
                                        ref="uploadConfig.fileUrl"
                                        :action="uploadConfig.uploadType"
                                        :on-success="handleUploadSuccess"
                                    >
                                        <el-button type="primary"
                                            >上传</el-button
                                        >
                                        <template #tip>
                                            <div class="el-upload__tip">
                                                jpg/png files with a size less
                                                than 500KB.
                                            </div>
                                        </template>
                                    </el-upload>
                                </el-col>
                            </el-row>
                        </div>
                    </template>
                </base-form>
            </div>
            <!-- 修改 -->
            <div v-if="dialogConfig.key === 'updateTableData'">
                <base-form
                    :formItems="updateFormConfig.formItems"
                    :formData="updateFormConfig.formSubmit"
                    :formConfig="updateFormConfig.formConfig"
                    :formRules="updateFormConfig.formRule"
                    ref="updateForm"
                    @onButtonClick="updateFormButtonClick"
                >
                    <template slot="uploadBoundry">
                        <div class="upload-container">
                            <el-row>
                                <el-col :span="2">
                                    <span>图标</span>
                                </el-col>
                                <el-col :span="16">
                                    <el-upload
                                        ref="uploadConfig.fileUrl"
                                        :action="uploadConfig.uploadType"
                                        :on-success="handleUploadSuccess"
                                    >
                                        <el-button type="primary"
                                            >上传</el-button
                                        >
                                        <template #tip>
                                            <div class="el-upload__tip">
                                                jpg/png files with a size less
                                                than 500KB.
                                            </div>
                                        </template>
                                    </el-upload>
                                </el-col>
                            </el-row>
                        </div>
                    </template>
                </base-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="handelCloseDialog"
                    >取 消</el-button
                >
                <el-button
                    size="small"
                    type="primary"
                    @click="handelCofimeDialog"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>
<script>
import BaseForm from '@/components/baseForm/index'
import DataOptions from '@/components/dataOptions/index'
import BaseTable from '@/components/baseTable/index'
import PaginAtion from '@/components/pagination/index'
import baseTransfer from '@/components/baseTransfer/index'
import globalMixin from '@/mixins/global'
import {
    zsyAdd,
    zsyDel,
    zsyPageList,
    zsyUpdate
} from '@/http/apis/water/zsy/index'
import { assemblyDataByTableColumn, setFormItemProp } from '@/utils/tool'

import { deviceTypeListAll } from '@/http/apis/water/deviceType/index'

export default {
    components: {
        BaseForm,
        DataOptions,
        BaseTable,
        PaginAtion,
        baseTransfer
    },
    mixins: [globalMixin],
    data() {
        return {
            uploadConfig: {
                areaId: '',
                uploadType: process.env.VUE_APP_BASE_HOST + '/tool/file/upload',
                listType: 'picture-card',
                fileUrl: '',
                fileName: '',
                dialogImageUrl: ''
            },
            // 搜索表单配置
            searchFormConfig: {
                formItems: [
                    [
                        {
                            ltype: 'select',
                            multiple: false,
                            options: [],
                            placeholder: '请选择设备',
                            width: 'w-auto',
                            label: '设备名称',
                            prop: 'deviceId'
                        },
                        {
                            ltype: 'button', // 大类型（input）
                            type: 'primary',
                            text: '搜索', // 文字提示
                            prop: 'searchDatas', // 绑定的key
                            icon: 'el-icon-search',
                            width: 'w-auto',
                            loading: false
                        },
                        {
                            ltype: 'button', // 大类型（input）
                            type: 'default',
                            text: '重置', // 文字提示
                            prop: 'resetSearchForm', // 绑定的key
                            icon: 'el-icon-refresh-right',
                            width: 'w-auto'
                        }
                    ]
                ],
                formSubmit: {
                    //TODO
                    name: ''
                },
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: 'auto'
                },
                // 搜索控件是否显示
                searchContenerShow: true
            },
            // 数据操作项配置
            dataOptionConfig: {
                // 左侧按钮配置
                leftConfig: [
                    {
                        prop: 'addTableData',
                        label: '新增',
                        icon: 'el-icon-plus',
                        type: 'primary',
                        disabled: false,
                        hasPermi: ['device/dict/save']
                    },
                    {
                        prop: 'deleteTableData',
                        label: '删除',
                        icon: 'el-icon-delete',
                        type: 'danger',
                        disabled: false,
                        hasPermi: ['device/dict/delete']
                    }
                ],
                // 右侧按钮配置
                rightConfig: [
                    {
                        prop: 'switchSearchStatus',
                        icon: 'el-icon-sort',
                        type: 'info',
                        disabled: false,
                        label: '搜索显隐'
                    },
                    {
                        prop: 'refreshTableData',
                        icon: 'el-icon-refresh-right',
                        type: 'info',
                        disabled: false,
                        label: '刷新'
                    },
                    {
                        prop: 'switchTableColumn',
                        icon: 'el-icon-menu',
                        type: 'info',
                        disabled: false,
                        label: '列显隐'
                    },
                    {
                        prop: 'fullTableContener',
                        icon: 'el-icon-full-screen',
                        type: 'info',
                        disabled: false,
                        label: '全屏'
                    }
                ]
            },
            // 表格配置
            baseTableConfig: {
                tableData: [],
                tableHeader: [
                    //TODO
                    {
                        type: 'selection',
                        width: 50,
                        fixed: 'left',
                        label: '选择',
                        visible: true
                    },
                    {
                        type: 'index',
                        label: '序号',
                        width: 50,
                        fixed: 'left',
                        visible: true
                    },
                    {
                        prop: 'deviceName',
                        label: '设备名称',
                        align: 'center',
                        visible: true,
                        width: 100,
                        showOverflowTooltip: true
                    },
                    {
                        prop: 'sys',
                        label: '蒸渗仪系统',
                        align: 'center',
                        visible: true,
                        showOverflowTooltip: true
                    },
                    {
                        prop: 'sid',
                        label: '设备编号',
                        align: 'center',
                        visible: true,
                        showOverflowTooltip: true
                    },
                    {
                        prop: 'time',
                        label: '设备时间',
                        align: 'center',
                        visible: true,
                        showOverflowTooltip: true
                    },
                    {
                        prop: 'sid',
                        label: '设备编号',
                        align: 'center',
                        visible: true,
                        showOverflowTooltip: true
                    },
                    {
                        prop: 'zslz',
                        label: '时段蒸散量',
                        align: 'center',
                        visible: true,
                        showOverflowTooltip: true
                    },
                    {
                        label: '操作',
                        minWidth: 100,
                        align: 'center',
                        type: 'handle',
                        visible: true
                    }
                ],
                tableConfig: {
                    loading: false
                },
                // 选中的表格数据
                tableCheckedDatas: []
            },
            // 分页配置
            paginationConfig: {
                type: 'md',
                size: 10,
                total: 100
            },
            // 弹框配置
            dialogConfig: {
                // 弹框标题
                title: '新增',
                // 是否显示
                show: false,
                // 宽度
                width: '30%',
                // 弹框标识(用来区分弹框内容)
                key: ''
            },
            // 查询表格数据的参数
            queryTableParams: {
                pageNo: 0,
                pageSize: 10,
                entity: {}
            },
            // 表格列筛选配置
            tableColumnTransferConfig: {
                // 穿梭框的数据
                data: [],
                // 穿梭框的标题
                titles: ['显示', '隐藏']
            },
            // 新增表单配置
            addFormConfig: {
                // 表单项
                formItems: [
                    [
                        {
                            ltype: 'select',
                            multiple: false,
                            options: [],
                            placeholder: '请选择设备',
                            prop: 'deviceId',
                            label: '设备'
                        }
                    ],
                    [
                        {
                            ltype: 'input',
                            nplaceholder: '请输入蒸渗仪系统',
                            label: '蒸渗仪系统',
                            prop: 'sys'
                        },
                        {
                            ltype: 'input',
                            nplaceholder: '请输入设备编号',
                            label: '设备编号',
                            prop: 'sid'
                        }
                    ],
                    [
                        {
                            ltype: 'datePicker',
                            nplaceholder: '请输入设备时间',
                            label: '设备时间',
                            prop: 'time',
                            valueFormat: 'yyyy-MM-dd HH:mm:ss'
                        },
                        {
                            ltype: 'input',
                            nplaceholder: '请输入设时段蒸散量',
                            label: '时段蒸散量',
                            prop: 'zslz'
                        }
                    ]
                ],
                // 提交项
                formSubmit: {
                    id: '',
                    deviceId: '',
                    sys: '',
                    sid: '',
                    time: '',
                    zslz: ''
                },
                // 配置项
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: '80px'
                },
                // 验证项
                formRule: {
                    deviceId: [
                        {
                            required: true,
                            message: '请选择设备',
                            trigger: 'blur'
                        }
                    ]
                }
            },

            // 修改表单配置
            updateFormConfig: {
                // 表单项
                formItems: [
                    [
                        {
                            ltype: 'select',
                            multiple: false,
                            options: [],
                            placeholder: '请选择设备',
                            prop: 'deviceId',
                            label: '设备'
                        }
                    ],
                    [
                        {
                            ltype: 'input',
                            nplaceholder: '请输入蒸渗仪系统',
                            label: '蒸渗仪系统',
                            prop: 'sys'
                        },
                        {
                            ltype: 'input',
                            nplaceholder: '请输入设备编号',
                            label: '设备编号',
                            prop: 'sid'
                        }
                    ],
                    [
                        {
                            ltype: 'datePicker',
                            nplaceholder: '请输入设备时间',
                            label: '设备时间',
                            prop: 'time',
                            valueFormat: 'yyyy-MM-dd HH:mm:ss'
                        },
                        {
                            ltype: 'input',
                            nplaceholder: '请输入设时段蒸散量',
                            label: '时段蒸散量',
                            prop: 'zslz'
                        }
                    ]
                ],
                // 提交项
                formSubmit: {
                    id: '',
                    deviceId: '',
                    sys: '',
                    sid: '',
                    time: '',
                    zslz: ''
                },
                // 配置项
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: '80px'
                },
                // 验证项
                formRule: {
                    deviceId: [
                        {
                            required: true,
                            message: '请选择设备',
                            trigger: 'blur'
                        }
                    ]
                }
            },
            deviceTypeDictData: []
        }
    },
    created() {
        /**
         * 初始化页面数据
         */
        this.initPage()
    },
    methods: {
        /**
         * 页面开始
         */
        async initPage() {
            /**
             * 查询表格
             */
            this.queryTableData(this.queryTableParams)
            this.getDeviceTypeDict()
        },

        /**
         * 中间表格相关
         */
        /**
         * 查询表格数据
         */
        async queryTableData(params) {
            this.baseTableConfig.tableConfig.loading = true
            let res = await zsyPageList(params)
            if (res.data) {
                console.log('this.deviceTypeDictData', this.deviceTypeDictData)
                res.data.list.forEach(val => {
                    val.deviceName = this.deviceTypeDictData.find(
                        item => item.value == val.deviceId
                    ).label
                })
                this.baseTableConfig.tableData = res.data.list
                this.paginationConfig.total = res.data.totalCount
            } else {
                this.baseTableConfig.tableData = []
                this.paginationConfig.total = 0
            }
            this.baseTableConfig.tableConfig.loading = false
        },

        /**
         * 获取设备字典信息
         * */
        async getDeviceTypeDict() {
            let res = await deviceTypeListAll({ devType: 7 })
            if (res.data) {
                res.data.forEach(item => {
                    let obj = {
                        label: item.sbmc,
                        value: item.id
                    }
                    this.deviceTypeDictData.push(obj)
                })

                this.searchFormConfig.formItems = setFormItemProp(
                    this.searchFormConfig.formItems,
                    'deviceId',
                    'options',
                    this.deviceTypeDictData
                )
                this.addFormConfig.formItems = setFormItemProp(
                    this.addFormConfig.formItems,
                    'deviceId',
                    'options',
                    this.deviceTypeDictData
                )
                this.updateFormConfig.formItems = setFormItemProp(
                    this.updateFormConfig.formItems,
                    'deviceId',
                    'options',
                    this.deviceTypeDictData
                )
            }
        },

        /**
         * 表格数据被选中
         */
        tableDataSelected(rows) {
            this.baseTableConfig.tableCheckedDatas = rows
        },

        /**
         * 初始化查询参数
         */
        initQueryParmas() {
            this.queryTableParams = {
                pageNo: 0,
                pageSize: 10,
                entity: {}
            }
            this.baseTableConfig.tableData = []
        },

        /**
         * 初始化新增表单
         */
        initAddForm() {
            this.addFormConfig.formSubmit = {
                id: '',
                deviceId: '',
                sys: '',
                sid: '',
                time: '',
                zslz: ''
            }
            this.$refs.addForm.resetForm()
        },

        /**
         * 页码变化
         */
        pageNumberChange(e) {
            this.queryTableParams.pageNo = e
            this.queryTableData(this.queryTableParams)
        },
        /**
         * 页大小变化
         */
        pageSizeChange(e) {
            // 页大小变化时，将当前页码设置为0
            this.queryTableParams.pageNo = 0
            // 将当前表格数据设置为空
            this.baseTableConfig.tableData = []
            this.queryTableParams.pageSize = e
            this.queryTableData(this.queryTableParams)
        },

        /**
         * 搜索栏相关
         */
        /**
         * 搜索按钮点击
         * @param {Object} params
         */
        searchButtonClick(params) {
            // 清空查询参数
            this.initQueryParmas()
            try {
                this[params.prop]()
            } catch (error) {
                throw new Error(error)
            }
        },

        /**
         * 重置搜索表单
         */
        resetSearchForm() {
            // 查询参数初始化
            this.initQueryParmas()
            // 重置搜索表单
            this.$refs.searchForm.resetForm()
            // 重新查询数据
            this.queryTableData(this.queryTableParams)
        },

        /**
         * 搜索数据
         */

        searchDatas() {
            this.$refs.searchForm.submitForm(() => {
                // 清空查询参数
                this.initQueryParmas()
                // 组装查询条件
                this.queryTableParams.entity = {
                    ...this.searchFormConfig.formSubmit
                }
                // 查询数据
                this.queryTableData(this.queryTableParams)
            })
        },

        /**
         * 操作栏相关
         */
        /**
         * 操作项点击
         * @param {*} params
         */
        handelOptionClick(params) {
            this[params] ? this[params]() : null
        },
        /**
         * 切换搜索栏的显示状态
         */
        switchSearchStatus() {
            this.searchFormConfig.searchContenerShow = !this.searchFormConfig
                .searchContenerShow
        },
        /**
         * 刷新表格数据
         */
        refreshTableData() {
            this.initQueryParmas()
            this.queryTableData(this.queryTableParams)
        },

        /**
         * 设置表格显示隐藏列(弹框确认)
         */
        switchTableColumnButtonClick() {
            let newData = this.$refs.baseTransfer.backCheckedData()
            if (newData && newData.length > 0) {
                this.baseTableConfig.tableHeader.forEach(ele => {
                    ele.visible = !newData.includes(ele.label)
                })
            } else {
                this.baseTableConfig.tableHeader.forEach(ele => {
                    ele.visible = true
                })
            }
            this.handelCloseDialog()
        },

        /**
         * 设置表格显示隐藏列
         */
        switchTableColumn() {
            let dialogParams = {
                title: '显示/隐藏',
                width: 'auto',
                show: true,
                key: 'tableColumn'
            }
            this.tableColumnTransferConfig.data = assemblyDataByTableColumn(
                this.baseTableConfig.tableHeader,
                'label',
                ['选择', '操作']
            )
            this.handelOpenDialog(dialogParams)
        },

        /**
         * 新增表格数据
         */
        addTableData() {
            let dialogParams = {
                title: '新增',
                width: '50%',
                show: true,
                key: 'addTableData'
            }
            this.handelOpenDialog(dialogParams)
            this.$nextTick(() => {
                this.initAddForm()
            })
        },

        /**
         * 新增数据确认提交
         */
        addFormButtonClick() {
            this.$refs['addForm'].submitForm(async res => {
                res.logo = this.uploadConfig.fileUrl
                let assRes = await zsyAdd(res)
                if (assRes && assRes.code === 0) {
                    this.$message.closeAll()
                    this.$message.success({ message: '新增成功！' })
                    this.initAddForm()
                } else {
                    this.$message.closeAll()
                    this.$message.error({ message: '新增失败！' })
                }
                this.handelCloseDialog()
                // 查询数据
                this.refreshTableData()
            })
        },

        /**
         * 修改表格数据打开弹窗
         */
        async updateTableData(row) {
            this.updateFormConfig.formSubmit = row
            let dialogParams = {
                title: '修改',
                width: '50%',
                show: true,
                key: 'updateTableData'
            }
            this.handelOpenDialog(dialogParams)
        },
        /**
         * 修改数据提交(弹框确认)
         */
        updateFormButtonClick() {
            this.$refs['updateForm'].submitForm(async res => {
                if (res) {
                    res.logo = this.uploadConfig.fileUrl
                    let assRes = await zsyUpdate(res)
                    if (assRes && assRes.code === 0) {
                        this.$message.closeAll()
                        this.$message.success({ message: '修改成功！' })
                    } else {
                        this.$message.closeAll()
                        this.$message.error({ message: '修改失败！' })
                    }
                    this.handelCloseDialog()
                    // 查询数据
                    this.refreshTableData()
                }
            })
        },

        /**
         * 删除表格数据
         */
        deleteTableData(rows) {
            if (
                typeof rows === 'undefined' &&
                this.baseTableConfig.tableCheckedDatas.length > 0
            ) {
                rows = this.baseTableConfig.tableCheckedDatas
            }
            if (typeof rows !== 'undefined') {
                let params = []
                if (Array.isArray(rows) && rows.length) {
                    for (let i = 0; i < rows.length; i++) {
                        const element = rows[i]
                        params.push(element.id)
                    }
                } else {
                    params = [rows.id]
                }
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(async () => {
                        let res = await zsyDel(params)
                        if (res && res.code == 0) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            })
                        } else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            })
                        }
                        // 查询数据
                        this.refreshTableData()
                    })
                    .catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        })
                    })
            } else {
                this.$message({
                    type: 'error',
                    message: '请选择数据！'
                })
            }
        },

        /**
         * 弹框相关
         */

        /**
         * 打开弹框
         * @param {*} params
         */
        handelOpenDialog(params) {
            this.dialogConfig = params
        },
        /**
         * 初始化弹框
         */
        handelInitDialog() {
            this.dialogConfig = {
                title: '',
                show: false,
                width: '',
                key: ''
            }
        },
        /**
         * 关闭弹框
         */
        handelCloseDialog() {
            this.handelInitDialog()
        },

        /**
         * 弹框确定
         */
        handelCofimeDialog() {
            // 表格列筛选的弹框
            if (this.dialogConfig.key === 'tableColumn') {
                this.switchTableColumnButtonClick()
            } else if (this.dialogConfig.key === 'addTableData') {
                this.addFormButtonClick()
            } else if (this.dialogConfig.key === 'updateTableData') {
                this.updateFormButtonClick()
            }
        },
        handleUploadSuccess(res, file) {
            const baseUrl = process.env.VUE_APP_BASE_HOST
            if (res && res.code === 0) {
                const url = new URL(res.data)
                const relativeUrl = url.pathname + url.search + url.hash
                this.uploadConfig.fileUrl = baseUrl + relativeUrl
                this.uploadConfig.fileName = file.name
            } else {
                this.$message.closeAll()
                this.$message.error({ message: '上传失败！' })
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.upload-container {
    width: 100%;
    height: 9vh;

    .el-col > span {
        color: rgb(144, 146, 153);
        margin-left: 45%;
        width: 80px;
    }
}
</style>
